package org.example.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.ProductEsBean;
import org.example.bean.SUserBehaviorHis;
import org.example.common.MqConstants;
import org.example.dao.ProductEsDao;
import org.example.service.impl.SUserBehaviorContextService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@RabbitListener(queues = MqConstants.BEHAVIORL_UPLOAD_QUEUE)
@Slf4j
public class BehaviorListener {
    @Autowired
    private SUserBehaviorContextService sUserBehaviorContextService;

    @RabbitHandler
    public void recieveMessage(Message msg, SUserBehaviorHis sUserBehaviorHis, Channel channel) throws InterruptedException {
        log.info("sUserBehaviorHis==============="+ JSON.toJSONString(sUserBehaviorHis));
        //{"idManager":"manager1","idPoster":"poster1","idUser":"user155","moduleType":"act","nowTime":"2023-11-25","type":"uv"}
        byte[] body = msg.getBody();
        // 消息头属性信息
        MessageProperties messageProperties = msg.getMessageProperties();

        System.out.println("消息处理完成！"+sUserBehaviorHis.getIdUser());
        // channel内按顺序自增的
        long deliveryTag = messageProperties.getDeliveryTag();
        System.out.println("deliveryTag:" + deliveryTag);

        try {
            sUserBehaviorContextService.getBehaviorUploadInstance(sUserBehaviorHis.getModuleType()).upload(sUserBehaviorHis,sUserBehaviorHis.getType());

            // 签收确认  multiple：是否批量签收确认  false:非批量签收
            channel.basicAck(deliveryTag, false);

            System.out.println("签收货物=====" + deliveryTag);

        } catch (IOException e) {
            // 网络中断
            throw new RuntimeException(e);
        }
    }
}
